﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using System.Net;
using ChatNetwork;
using System.Configuration;
using System.Windows.Forms;
using System.Linq;

namespace FAP.CaptchaCenter
{
    public delegate void ReceviceCaptchaHandeler(string _strCaptcha);

    public class CaptchaServer
    {
        private static Form1 m_server;
        public static ReceviceCaptchaHandeler OnReceviceCaptcha;
        private static bool m_isStarted = false;
        private static List<SendObject> m_lstCaptcha = new List<SendObject>();

        public static void StartServer()
        {
            string strServerAddress = ConfigurationSettings.AppSettings["ServerAddress"] == null ? "127.0.0.1" : ConfigurationSettings.AppSettings["ServerAddress"];
            string strServerPort = ConfigurationSettings.AppSettings["ServerPort"] == null ? "12345" : ConfigurationSettings.AppSettings["ServerPort"];
            try
            {
                if (m_server == null)
                    m_server = new Form1();
                m_server.m_strIP = strServerAddress;
                m_server.m_iPort = Int32.Parse(strServerPort);
                m_server.StartServer();
                m_server.OnReceviceCaptcha += OnReceviceCaptcha;
                m_server.OnClientConnected += OnClientConnected;
                m_server.OnClientDisconnected += OnClientDisconnected;
                m_isStarted = true;

                FAP.Cores.Console.FapConsole.WriteLine(string.Format("[CaptchaServer]: Started at {0}:{1}", strServerAddress, strServerPort), 1);
            }
            catch (Exception ex)
            {
                FAP.Cores.Console.FapConsole.WriteLine(string.Format("[CaptchaServer]: Can't start at {0}:{1}", strServerAddress, strServerPort), 4);
                FAP.Cores.Console.FapConsole.WriteLine(string.Format("[CaptchaServer]: {0}:{1}", ex.Message, ex.StackTrace), 4);
                throw ex;
            }
        }

        public static void OnClientConnected(ChatDialog client)
        {
            FAP.Cores.Console.FapConsole.WriteLine(string.Format("[CaptchaServer]: Client {0} connected at ", client.ClientID), 1);
            var listNeedToSend = m_lstCaptcha.Where(m => m.IsSent == false);
            foreach (var item in listNeedToSend)
            {
                //SendCaptcha(item.Content);
                client.ClientID = item.ClientID;
                client.Send(item.Content);
                item.IsSent = true;

                FAP.Cores.Console.FapConsole.WriteLine(string.Format("[CaptchaServer]: Send captcha request to client {0}.", item.ClientID), 1);

            }
        }

        public static void OnClientDisconnected(ChatDialog client)
        {
            //
        }

        public static void SendCaptcha(string _strCaptcha)
        {
            if (m_isStarted == false)
                throw new Exception("The server not started");
            if (OnReceviceCaptcha == null)
                throw new Exception("The OnRecevice function not set");
            //send captcha

            SendObject s = new SendObject(0, _strCaptcha);
            m_lstCaptcha.Add(s);
            FAP.Cores.Console.FapConsole.WriteLine(string.Format("[CaptchaServer]: Add captcha to List."), 1);
            ///m_lstCaptcha.Where(m => !m.IsSent).GroupBy(m => m.ClientID).ElementAt(0).ToArray();

            Random r = new Random();
            if (m_server.formArray.Count > 0)
            {
                ChatDialog ct = (ChatDialog)m_server.formArray[r.Next(0, m_server.formArray.Count)];
                ct.ClientID = ct.ClientID;
                ct.Send(_strCaptcha);
                s.IsSent = true;
                FAP.Cores.Console.FapConsole.WriteLine(string.Format("[CaptchaServer]: Send captcha request to client {0}.", ct.ClientID), 1);
            }
        }

        public static void StopServer()
        {
            m_server.StopServer();
            m_server = null;
            FAP.Cores.Console.FapConsole.WriteLine(string.Format("[CaptchaServer]: Stoped"), 1);
        }

    }

    class SendObject
    {
        public string Content;
        public int ClientID;
        public bool IsSent;
        public SendObject(int ClientID, string Content)
        {
            this.ClientID = ClientID;
            this.Content = Content;
        }
    }
}
